var express = require('express');
var router = express.Router();
var encryptUtils = require('../common/encryptutil');
var superagent = require('superagent');
var addressdao = require('../dao/addressdao');
var userdao = require('../dao/userdao');
var uuid = require('node-uuid');
/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('login', { tip: '' });
});

router.get('/login', function (req, res, next) {
  res.render('login', { tip: '' });
});

router.get('/download', function (req, res, next) {
  res.render('download');
});

router.get('/stop', function (req, res, next) {
  res.render('stop');
});

router.post('/login', function (req, res, next) {
  var username = req.body.username;
  var password = req.body.password;

  if (username == 'admin18175966677' && password == '18175966677') {
    var clientid = req.body.clientid || uuid.v4().replace(new RegExp('-', 'gm'), '');
    res.cookie('clientid', clientid, { maxAge: 1000 * 60 * 60 * 24 * 30 });
    res.redirect('/users?clientid=' + clientid);
  } else {
    //获取第三方帐号
    userdao.getLoginInfo(username, password).then(function (result) {
      if (result[0].status == '1') {

        var id = result[0].id;//用户ID
        username = result[0].uname;
        password = result[0].pwd;

        var md5_password = encryptUtils.md5Encrypt(password);

        superagent
          .post('https://gateway.sioeye.cn/functions/login')
          .send({
            "username": username,
            "type": "web",
            "password": md5_password
          })
          .set({
            'x_sioeye_app_sign_key': '5b61bfedecd0ce3586884af200cf9657,1520316805',
            'X_Sioeye_App_Id': 'usYhGBBKDMiypaKFV8fc3kE4',
            'X_Sioeye_App_Production': 1
          })
          .end(function (err, response) {
            if (err) {
              //do something
              res.render('login', { tip: '帐户或密码错误' });
            } else {
              //do something
              //解析token
              var user = JSON.parse(response.text);
              if (user.success) {
                var data = {};
                //获取历史申请地址
                addressdao.getList(user.value.sessiontoken, id).then(function (result) {
                  //console.log(result);
                  res.render('address', { tip: 'false', token: user.value.sessiontoken, data: data, history: result, id: id });
                }, function (data_error) {
                  console.error(data_error);
                  res.render('address', { tip: 'false', token: user.value.sessiontoken, data: data, history: [], id: id });
                });


              } else {
                res.render('login', { tip: '帐户或密码错误' });
              }
            }
          })

      } else {
        res.render('login', { tip: '帐户已被禁止登录' });
      }

    }, function (data_error) {
      console.error(data_error);
      res.render('login', { tip: '帐户或密码错误' });
    });
  }
});


router.post('/apply', function (req, res, next) {
  var token = req.body.token;
  var title = req.body.title;
  var id = req.body.id;

  superagent
    .post('https://gateway.sioeye.cn/functions/live_apply')
    .send({
      "devName": "device0",
      "deviceId": "000" + id
    })
    .set({
      'x_sioeye_app_sign_key': '5b61bfedecd0ce3586884af200cf9657,1520316805',
      'X_Sioeye_App_Id': 'usYhGBBKDMiypaKFV8fc3kE4',
      'X_Sioeye_App_Production': 1,
      'x_sioeye_sessiontoken': token
    })
    .end(function (err, response) {
      if (err) {
        //do something
        res.send(err);
      } else {
        //do something
        var data = JSON.parse(response.text);

        //保存数据
        var live = {};



        var s = data.value.pushurl;
        //获取liveid
        var liveid = data.value.liveid;

        live.liveid = liveid;

        var rtmp_header = s.substring(0, s.lastIndexOf('/'));//rtmp://c-push.sioeye.cn/sioeyecn
        var streamid = s.substring(s.lastIndexOf('/') + 1, s.lastIndexOf('-'));//JjuQfq

        live.rtmp = rtmp_header;

        var stream = s.substring(s.lastIndexOf('/') + 1, s.length);
        live.streamid = stream;

        live.hls = 'https://c-hls.sioeye.cn/sioeyecn/' + streamid + '.m3u8';
        //$('#rtmp').val('rtmp://c-live.sioeye.cn/sioeyecn/' + streamid);

        var nowDate = new Date();
        var year = nowDate.getFullYear();
        var month = nowDate.getMonth() + 1 < 10 ? "0" + (nowDate.getMonth() + 1)
          : nowDate.getMonth() + 1;
        var day = nowDate.getDate() < 10 ? "0" + nowDate.getDate() : nowDate
          .getDate();
        var dateStr = year + "-" + month + "-" + day;

        var replaymp4 = 'https://k-replay.sioeye.cn/' + dateStr + '/' + liveid + '/' + liveid + '.mp4';
        var replaym3u8 = 'https://k-replay.sioeye.cn/' + dateStr + '/' + liveid + '/' + liveid + '.m3u8';

        live.replaymp4 = replaymp4;
        live.replaym3u8 = replaym3u8;
        live.userid = token;
        live.title = title;
        live.uid = id;

        addressdao.insert(live).then(function (result) {
          console.log(result);
        }, function (data_error) {
          console.error(data_error);
        });
        res.send(data.value);
      }
    })
});

router.post('/download', function (req, res, next) {
  var url = req.body.url;
  var conversationid = url.substring(url.lastIndexOf('/') + 1);
  if (conversationid.length == 32) {
    superagent
      .post('https://gateway.sioeye.cn/functions/multi_info')
      .send({
        "conversationId": conversationid
      })
      .set({
        'x_sioeye_app_sign_key': '5b61bfedecd0ce3586884af200cf9657,1520316805',
        'X_Sioeye_App_Id': 'usYhGBBKDMiypaKFV8fc3kE4',
        'X_Sioeye_App_Production': 1
      })
      .end(function (err, response) {
        if (err) {
          //do something
          res.send(err);
        } else {
          //do something
          var data = JSON.parse(response.text);
          if (data.success) {
            var livelist = data.value.livelist;
            var ret = { livelist: livelist, title: data.value.title };
            res.send(ret);
          } else {
            res.send([]);
          }
        }
      })

  }
});

router.post('/reseturl', function (req, res, next) {
  var liveid = req.body.liveid;
  var token = req.body.token;
  superagent
    .post('https://gateway.sioeye.cn/functions/search_conversationid_by_liveid')
    .send({
      "liveId": liveid
    })
    .set({
      'x_sioeye_app_sign_key': '5b61bfedecd0ce3586884af200cf9657,1520316805',
      'X_Sioeye_App_Id': 'usYhGBBKDMiypaKFV8fc3kE4',
      'X_Sioeye_App_Production': 1,
      'x_sioeye_sessiontoken': token
    })
    .end(function (err, response) {
      if (err) {
        //do something
        res.send(err);
      } else {
        //do something
        var data = JSON.parse(response.text);
        var conversationid = data.value.conversationid;

        //获取视频信息
        superagent
          .post('https://gateway.sioeye.cn/functions/multi_info')
          .send({
            "conversationId": conversationid
          })
          .set({
            'x_sioeye_app_sign_key': '5b61bfedecd0ce3586884af200cf9657,1520316805',
            'X_Sioeye_App_Id': 'usYhGBBKDMiypaKFV8fc3kE4',
            'X_Sioeye_App_Production': 1,
            'x_sioeye_sessiontoken': token
          })
          .end(function (err, response) {
            if (err) {
              //do something
              res.send(err);
            } else {
              //do something
              var data = JSON.parse(response.text);
              if (data.success) {
                var startdate = data.value.startdate;
                var dateStr = (new Date(startdate * 1000 - 3600 * 8 * 1000)).format("yyyy-MM-dd");//东8区转0时区
                var replaymp4 = 'https://k-replay.sioeye.cn/' + dateStr + '/' + liveid + '/' + liveid + '.mp4';
                var replaym3u8 = 'https://k-replay.sioeye.cn/' + dateStr + '/' + liveid + '/' + liveid + '.m3u8';
                addressdao.reseturl(liveid, replaymp4, replaym3u8).then(function (result) {
                  //console.log(result);
                }, function (data_error) {
                  console.error(data_error);
                });
                res.send(data);
              } else {
                res.send(data);
              }
            }
          })
      }
    })
});

router.get('/api/stream', function (req, res, next) {
  //以下token为sioeye系统帐号为sunshine的vip帐号
  var token = '7NyyA2M6wmX2hnbA4ZksZ7fJYfQ4tybE';//req.body.token;
  var title = req.body.title;
  var id = req.query.id;

  superagent
    .post('https://gateway.sioeye.cn/functions/live_apply')
    .send({
      "devName": "device0",
      "deviceId": "cloud_" + id
    })
    .set({
      'x_sioeye_app_sign_key': '5b61bfedecd0ce3586884af200cf9657,1520316805',
      'X_Sioeye_App_Id': 'usYhGBBKDMiypaKFV8fc3kE4',
      'X_Sioeye_App_Production': 1,
      'x_sioeye_sessiontoken': token
    })
    .end(function (err, response) {
      if (err) {
        res.send(err);
      } else {
        var data = JSON.parse(response.text);

        //数据对象
        var live = {};



        var s = data.value.pushurl;
        //获取liveid
        var liveid = data.value.liveid;

        live.liveid = liveid;

        var rtmp_header = s.substring(0, s.lastIndexOf('/'));//rtmp://c-push.sioeye.cn/sioeyecn
        var streamid = s.substring(s.lastIndexOf('/') + 1, s.lastIndexOf('-'));//JjuQfq

        live.rtmp = rtmp_header;

        var stream = s.substring(s.lastIndexOf('/') + 1, s.length);
        live.streamid = stream;

        live.hls = 'https://c-hls.sioeye.cn/sioeyecn/' + streamid + '.m3u8';

        var nowDate = new Date();
        var year = nowDate.getFullYear();
        var month = nowDate.getMonth() + 1 < 10 ? "0" + (nowDate.getMonth() + 1)
          : nowDate.getMonth() + 1;
        var day = nowDate.getDate() < 10 ? "0" + nowDate.getDate() : nowDate
          .getDate();
        var dateStr = year + "-" + month + "-" + day;

        var replaymp4 = 'https://k-replay.sioeye.cn/' + dateStr + '/' + liveid + '/' + liveid + '.mp4';
        var replaym3u8 = 'https://k-replay.sioeye.cn/' + dateStr + '/' + liveid + '/' + liveid + '.m3u8';


        live.replaymp4 = replaymp4;
        live.replaym3u8 = replaym3u8;
        live.userid = token;
        live.uid = id;

        res.send(live);

      }
    })
});

Date.prototype.format = function (format) {
  var o = {
    "M+": this.getMonth() + 1,
    // month
    "d+": this.getDate(),
    // day
    "h+": this.getHours(),
    // hour
    "m+": this.getMinutes(),
    // minute
    "s+": this.getSeconds(),
    // second
    "q+": Math.floor((this.getMonth() + 3) / 3),
    // quarter
    "S": this.getMilliseconds()
    // millisecond
  };
  if (/(y+)/.test(format) || /(Y+)/.test(format)) {
    format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  }
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(format)) {
      format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
    }
  }
  return format;
};

router.post('/devicelist', function (req, res, next) {
  var sioeyeid = req.body.sioeyeid||'';
  //根据sioeyeid获取token
  async function getToken() {
    var ret = await superagent
      .post('http://899a4f89.ngrok.io/devicelist')
      .send({
        'sioeyeid': sioeyeid
      })
      .set({
        'Content-Type': 'application/x-www-form-urlencoded'
      });
    res.send(ret.body);
  }
  getToken();
});

router.post('/stop', function (req, res, next) {
  var token = req.body.sessiontoken;
  var deviceId = req.body.deviceid;
  var devName = req.body.devicename;
  async function liveApply() {
    var ret = await superagent
      .post('https://gateway.sioeye.cn/functions/live_apply')
      .send({
        "devName": devName,
        "deviceId": deviceId
      })
      .set({
        'x_sioeye_app_sign_key': '5b61bfedecd0ce3586884af200cf9657,1520316805',
        'X_Sioeye_App_Id': 'usYhGBBKDMiypaKFV8fc3kE4',
        'X_Sioeye_App_Production': 1,
        'x_sioeye_sessiontoken': token,
        'Host': 'gateway.sioeye.cn',
        'user-Agent': 'okhttp/3.3.1',
        'Accept-Encoding': 'gzip',
        'Content-Type': 'application/json; charset=UTF-8'
      });
    console.log(ret.text);
    res.send(JSON.parse(ret.text));
  }

  liveApply();
});

module.exports = router;
